package com.hqully.smartfumehood.controller;


import com.github.pagehelper.PageInfo;
import com.hqully.smartfumehood.common.utils.PermissionUtil;
import com.hqully.smartfumehood.common.utils.ResultVoUtil;
import com.hqully.smartfumehood.common.vo.QueryVo;
import com.hqully.smartfumehood.common.vo.ResultVo;
import com.hqully.smartfumehood.entity.Unit;
import com.hqully.smartfumehood.service.UnitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *     单位控制器
 * </p>
 * @author liulingyu
 * @date 2022-05-18 19:45
 * @version 1.0
 */
@RestController
@RequestMapping("/api/unit")
public class UnitController extends BaseController{
    @Autowired
    private UnitService unitService;

    @PostMapping("/find-all-unit")
    public ResultVo findAllUnit(@RequestHeader("token") String token, @RequestBody QueryVo queryVo){

        QueryVo realQueryVo = PermissionUtil.setQueryUnitId(token, queryVo);

        PageInfo<Unit> allUnit = unitService.findAllUnit(realQueryVo);


        return ResultVoUtil.success(allUnit);
    }

    @PostMapping("/add-unit")
    public ResultVo addUnit(@RequestBody Unit unit){
        try {
            int status = unitService.addUnit(unit);
        } catch (DuplicateKeyException e) {

            return ResultVoUtil.error("该单位已存在");
        }


        return ResultVoUtil.success("添加单位成功");
    }

    @PostMapping("/delete-unit")
    public ResultVo deleteUnit(@RequestBody Unit unit){
        unitService.deleteUnit(unit.getId());

        return ResultVoUtil.success("删除单位成功");
    }

    @PostMapping("/update-unit")
    public ResultVo updateUnit(@RequestBody Unit unit){
        unitService.updateUnit(unit);

        return ResultVoUtil.success("更新单位成功");
    }

}
